﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace QLK.Database.DALs
{
    public class EmployeeDAL
    {
        private ManageStoreDataContext db;

        public EmployeeDAL()
        {
            db = new ManageStoreDataContext();
        }

        public List<Employee> EmployeeGetAll()
        {
            var Emps = from emp in db.Employees
                       orderby emp.LastName
                       select emp;

            return Emps.ToList<Employee>();
        }

        public Employee EmployeeGetByID(int EmpID)
        {
            Employee Emp = db.Employees.Single<Employee>(emps => emps.EmployeeID == EmpID);

            return Emp;
        }

        public bool EmployeeInsert(Employee Emps)
        {
            try
            {
                db.Employees.InsertOnSubmit(Emps);
                db.SubmitChanges();
                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                return false;
            }
        }

        public bool EmployeeDeleteByID(int EmpID)
        {
            Employee Emp = db.Employees.Single<Employee>(emps => emps.EmployeeID == EmpID);

            if (Emp == null)
                return false;

            db.Employees.DeleteOnSubmit(Emp);

            try
            {
                db.SubmitChanges();
                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                return false;
            }
        }

        public bool EmployeeUpdate(Employee Emps)
        {
            Employee Emp = db.Employees.Single<Employee>(emps => emps.EmployeeID == Emps.EmployeeID);

            if (Emp == null)
                return false;

            Emp.LastName = Emps.LastName;
            Emp.FirstName = Emps.FirstName;
            Emp.Gender = Emps.Gender;
            Emp.IDCard = Emps.IDCard;
            Emp.PhoneNumber = Emps.PhoneNumber;

            try
            {
                db.SubmitChanges();
                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                return false;
            }
        }

        public bool EmployeeCheckDuplicateIDCard(string IDCard)
        {
            var Emps = from e in db.Employees
                       select e;
            if (Emps.ToList<Employee>().Count == 0)
                return true;
            else
            {
                Employee Emp = db.Employees.Single<Employee>(emps => emps.IDCard.Equals(IDCard));

                if (Emp == null)
                    return true;
                return false;
            }
        }
    }
}
